package run.autoium.utils;

import run.autoium.entity.MyHeader;
import run.autoium.entity.po.ProjectParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParamsUtils {

    public static String assemble(String target, List<ProjectParam> params) {
        int i = target.indexOf("{");
        int j = target.indexOf("}");
        int k = target.indexOf("$");
        if (i >= 0 && j >= 0 && k >= 0 && i < j) {
            String value = "";
            String name = target.substring(i + 1, j);
            for (int l = 0; l < params.size(); l++) {
                ProjectParam projectParam = params.get(l);
                if (projectParam.getName().equals(name)) {
                    value = projectParam.getValue();
                }
            }
            return StringUtils.replaceByIndexs(k, j, target, value);
        }
        return target;
    }

    public static Map<String, String> assemble(Map<String, String> map, List<ProjectParam> params) {
        Map<String, String> res = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            String newKey = assemble(key, params);
            String newValue = assemble(value, params);
            res.put(newKey, newValue);
        }
        return res;
    }

    public static List<MyHeader> assemble(List<MyHeader> headers, List<ProjectParam> params) {
        List<MyHeader> res = new ArrayList<>();
        for (int i = 0; i < headers.size(); ++i) {
            MyHeader h = headers.get(i);
            String key = h.getKey();
            String value = h.getValue();
            String newKey = assemble(key, params);
            String newValue = assemble(value, params);
            res.add(new MyHeader(newKey, newValue));
        }
        return res;
    }
}
